<template>
  <div class="app-container">
    <el-card class="box-card">
      <el-steps :active="currentStep" finish-status="success" class="steps">
        <el-step title="选择咨询师" />
        <el-step title="选择时间" />
        <el-step title="填写信息" />
        <el-step title="支付" />
      </el-steps>

      <!-- 步骤1：选择咨询师 -->
      <div v-show="currentStep === 0" class="step-content">
        <el-row :gutter="20">
          <el-col :span="8" v-for="item in counselors" :key="item.id">
            <el-card 
              class="counselor-card" 
              :class="{ 'selected': selectedCounselor?.id === item.id }"
              shadow="hover"
            >
              <div class="counselor-info">
                <div class="header">
                  <h3>{{ item.realName }}</h3>
                  <span class="title">{{ item.title }}</span>
                </div>
                <div class="specialty-tags">
                  <el-tag
                    v-for="tag in parseSpecialty(item.specialty)"
                    :key="tag"
                    size="small"
                    effect="plain"
                    class="specialty-tag"
                  >
                    {{ tag }}
                  </el-tag>
                </div>
                <div class="rating">
                  <el-rate
                    v-model="item.rating"
                    disabled
                    show-score
                    :max="5"
                    :score-template="''"
                  />
                  <span class="count">({{ item.consultationCount || 0 }}次咨询)</span>
                </div>
                <div class="introduction">{{ item.introduction }}</div>
              </div>
              <div class="actions">
                <el-button 
                  :type="selectedCounselor?.id === item.id ? 'success' : 'primary'"
                  @click="handleCounselorSelect(item)"
                >
                  {{ selectedCounselor?.id === item.id ? '取消选择' : '选择' }}
                </el-button>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 步骤2：选择时间 -->
      <div v-show="currentStep === 1" class="step-content">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-calendar v-model="selectedDate">
              <template #header="">
                <div class="calendar-header">
                  <span class="calendar-title">{{ calendarTitle }}</span>
                  <div class="calendar-controls">
                    <el-button-group class="year-control">
                      <el-button size="small" @click="changeYear(-1)">上一年</el-button>
                      <el-button size="small" @click="changeYear(1)">下一年</el-button>
                    </el-button-group>
                    <el-button-group class="month-control">
                      <el-button size="small" @click="selectPrevMonth">上个月</el-button>
                      <el-button size="small" @click="selectNextMonth">下个月</el-button>
                    </el-button-group>
                  </div>
                </div>
              </template>
              <template #dateCell="{ data }">
                <div 
                  class="calendar-cell" 
                  :class="{ 'selected': data.day === selectedDay }"
                  @click="handleDateClick(data.day)"
                >
                  <div class="date-text">{{ data.day.split('-')[2] }}</div>
                  <div class="schedule-content">
                    <template v-if="isCurrentMonth(data)">
                      <template v-if="hasScheduledSlots(data.day)">
                        <div 
                          v-for="slot in getDateTimeSlots(data.day)" 
                          :key="slot.timeSlot"
                          class="time-slot" 
                          :class="{ 
                            'selected': isTimeSlotSelected(slot.timeSlot),
                            'disabled': !isSlotAvailable(slot)
                          }"
                          @click="isSlotAvailable(slot) && handleTimeSelect(slot.timeSlot)"
                        >
                          <span class="time">{{ slot.timeSlot }}</span>
                          <el-tag 
                            size="small" 
                            :type="getSlotTagType(slot)"
                            :class="{ 'available': isSlotAvailable(slot) }"
                          >
                            {{ getSlotStatusText(slot) }}
                          </el-tag>
                        </div>
                      </template>
                      <template v-else-if="isPastDate(data.day)">
                        <el-tag
                          size="small"
                          type="info"
                          class="schedule-tag"
                        >
                          已过期
                        </el-tag>
                      </template>
                      <template v-else>
                        <el-tag
                          size="small"
                          type="info"
                          class="schedule-tag"
                        >
                          未排班
                        </el-tag>
                      </template>
                    </template>
                  </div>
                </div>
              </template>
            </el-calendar>
          </el-col>
          <el-col :span="12" class="time-slots-wrapper">
            <div class="time-slots-container" v-if="selectedDate">
              <h3>{{ formatDate(selectedDate) }} 可预约时段</h3>
              <el-row :gutter="10">
                <el-col :span="8" v-for="slot in availableTimeSlots" :key="slot.timeSlot">
                  <div 
                    class="time-slot" 
                    :class="{ 
                      'selected': isTimeSlotSelected(slot.timeSlot),
                      'disabled': !isSlotAvailable(slot) 
                    }"
                    @click="isSlotAvailable(slot) && handleTimeSelect(slot.timeSlot)"
                  >
                    <span class="time">{{ slot.timeSlot }}</span>
                    <el-tag 
                      size="small" 
                      :type="getSlotTagType(slot)"
                      :class="{ 'available': isSlotAvailable(slot) }"
                    >
                      {{ getSlotStatusText(slot) }}
                    </el-tag>
                  </div>
                </el-col>
              </el-row>
            </div>
          </el-col>
        </el-row>
      </div>

      <!-- 步骤3：填写信息 -->
      <div v-show="currentStep === 2" class="step-content">
        <el-form 
          :model="appointmentForm" 
          :rules="rules" 
          ref="appointmentFormRef"
          label-width="100px"
          class="appointment-form"
        >
          <el-form-item label="咨询类型" prop="type">
            <el-select 
              v-model="appointmentForm.type" 
              placeholder="请选择咨询类型"
            >
              <el-option 
                v-for="(label, value) in typeOptions" 
                :key="value" 
                :label="label" 
                :value="value" 
              />
            </el-select>
          </el-form-item>
          <el-form-item label="问题描述" prop="description">
            <el-input 
              type="textarea" 
              v-model="appointmentForm.description"
              rows="4"
              placeholder="请详细描述您想要咨询的问题..."
              maxlength="500"
              show-word-limit
            />
          </el-form-item>
        </el-form>
      </div>

      <!-- 步骤4：支付 -->
      <div v-show="currentStep === 3" class="step-content">
        <div class="payment-container">
          <el-card class="payment-card">
            <div class="payment-header">
              <div class="payment-title">订单支付</div>
              <div class="payment-status">
                <el-tag :type="getPaymentStatusType(paymentInfo.status)" effect="dark">
                  {{ getPaymentStatusLabel(paymentInfo.status) }}
                </el-tag>
              </div>
            </div>
            <el-divider />
            <div class="payment-content">
              <el-descriptions :column="1" border>
                <el-descriptions-item label="订单号">
                  <span class="order-no">{{ paymentInfo.orderNo || '-' }}</span>
                </el-descriptions-item>
                <el-descriptions-item label="支付金额">
                  <span class="amount">¥{{ paymentInfo.amount || '0.00' }}</span>
                </el-descriptions-item>
              </el-descriptions>
              <div class="payment-actions">
                <el-button 
                  type="primary" 
                  :loading="submitting"
                  @click="handleConfirmAndPay"
                  :disabled="paymentInfo.status === 'SUCCESS'"
                >
                  确认并支付
                </el-button>
              </div>
            </div>
          </el-card>
        </div>
      </div>

      <!-- 步骤控制按钮 -->
      <div class="step-actions">
        <el-button v-if="currentStep > 0 && paymentInfo.status !== 'SUCCESS'" @click="prevStep">上一步</el-button>
        <el-button 
          v-if="currentStep < 3" 
          type="primary" 
          @click="nextStep"
          :disabled="!canGoNext"
        >下一步</el-button>
        <el-button 
          v-else 
          type="primary" 
          @click="goToAppointmentList"
          :disabled="paymentInfo.status !== 'SUCCESS'"
        >查看预约</el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, watch, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getCounselorList, getAvailableTimeSlots } from '@/api/counseling'
import { createPayment, checkPaymentStatus, getCounselorPrice, getIncomeStatistics } from '@/api/payment'
import type { Counselor } from '@/types/counseling'
import type { PaymentStatus, PaymentInfo } from '@/types/payment'
import { useRouter } from 'vue-router'

const router = useRouter()
const paymentCompleted = ref(false)

// 步骤控制
const currentStep = ref(0)
const nextStep = async () => {
  if (currentStep.value === 0 && !selectedCounselor.value) {
    ElMessage.warning('请选择咨询师');
    return;
  }
  
  if (currentStep.value === 1 && !selectedTime.value) {
    ElMessage.warning('请选择预约时间');
    return;
  }
  
  if (currentStep.value === 2) {
    const valid = await appointmentFormRef.value?.validate();
    if (!valid) {
      return;
    }

    try {
      submitting.value = true;
      ElMessage.info('正在创建支付订单...');

      // 准备预约信息
      const appointmentInfo = {
        counselorId: selectedCounselor.value?.id,
        appointmentTime: `${formatDateToString(selectedDate.value)} ${selectedTime.value}`,
        type: appointmentForm.value.type,
        description: appointmentForm.value.description,
        price: selectedCounselor.value?.counselorPrice?.pricePerHour || 0
      };

      console.log('提交的预约信息:', appointmentInfo);
      
      // 创建支付订单
      const res = await createPayment(JSON.stringify(appointmentInfo));
      console.log('支付创建原始响应:', res);

      if (res.code === 200) {
        // 从响应中解析支付表单和订单号
        const formStr = res.data;
        console.log('支付表单字符串:', formStr);
        
        // 尝试多种方式匹配订单号
        // 修改正则表达式以匹配 biz_content 中的 out_trade_no
const orderNoMatch = formStr.match(/out_trade_no%22%3A%22([^%]+)%22/);
        console.log('订单号匹配结果:', orderNoMatch);
        
        // 如果第一种方式没匹配到，尝试其他方式
        let orderNo = '';
        if (orderNoMatch && orderNoMatch[1]) {
          orderNo = orderNoMatch[1];
        } else {
          // 尝试解析 JSON
          try {
            const jsonData = JSON.parse(formStr);
            orderNo = jsonData.out_trade_no || jsonData.orderNo;
            console.log('JSON解析结果:', jsonData);
          } catch (e) {
            console.log('JSON解析失败:', e);
          }
        }
        
        console.log('最终解析到的订单号:', orderNo);
        
        // 设置支付信息
        paymentInfo.value = {
          orderNo: orderNo,
          amount: appointmentInfo.price,
          status: 'PENDING',
          paymentUrl: formStr
        };

        console.log('设置的支付信息:', paymentInfo.value);
        
        ElMessage.success('支付订单创建成功，请点击"确认并支付"按钮进行支付');
        
      } else {
        console.error('创建支付订单失败:', res);
        ElMessage.error(res.message || '创建支付订单失败');
        return;
      }
    } catch (error) {
      console.error('创建支付订单失败:', error);
      ElMessage.error('创建支付订单失败，请稍后重试');
      return;
    } finally {
      submitting.value = false;
    }
  }

  currentStep.value++;
};

const prevStep = () => {
  if (currentStep.value > 0) {
    currentStep.value--
  }
}

// 修改步骤数组

// 修改当前步骤的最大值

// 扩展Counselor类型
interface ExtendedCounselor extends Counselor {
  counselorPrice?: {
    id: number;
    counselorId: number;
    pricePerHour: number;
    status: string;
  } | null;
}

// 咨询师选择
const counselors = ref<ExtendedCounselor[]>([])
const selectedCounselor = ref<ExtendedCounselor | null>(null)

const loadCounselors = async () => {
  try {
    const res = await getCounselorList({
      pageNum: 1,
      pageSize: 100
    })
    if (res.code === 200) {
      counselors.value = res.data.records.map(item => ({
        ...item,
        rating: Number(item.rating) || 0,
        consultationCount: item.consultationCount || 0,
        specialty: Array.isArray(item.specialty) ? item.specialty : parseSpecialty(item.specialty),
        counselorPrice: null
      }))
      
      // 获取每个咨询师的价格
      for (const counselor of counselors.value) {
        try {
          const { data: priceRes } = await getCounselorPrice(counselor.id)
          counselor.counselorPrice = priceRes || null
        } catch (error) {
          console.error(`获取咨询师${counselor.id}的价格失败:`, error)
        }
      }
    }
  } catch (error) {
    console.error('加载咨询师列表失败:', error)
  }
}

const handleCounselorSelect = (counselor: ExtendedCounselor) => {
  if (selectedCounselor.value?.id === counselor.id) {
    selectedCounselor.value = null
  } else {
    selectedCounselor.value = counselor
  }
}

// 时间选择
const selectedDate = ref<Date>(new Date())
const selectedDay = ref<string>('')
const selectedTime = ref<string>('')
const availableTimeSlots = ref<any[]>([])

const formatDateToString = (date: Date): string => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

const isTimeSlotSelected = (time: string): boolean => {
  return selectedTime.value === time.split('-')[0]
}


// 咨询类型选项
const typeOptions = {
  PERSONAL: '个人成长',
  ACADEMIC: '学业问题',
  EMOTIONAL: '情感困扰',
  OTHER: '其他'
} as const

// 预约表单
const appointmentForm = ref({
  type: '',
  description: ''
})

// 表单规则
const rules = {
  type: [{ required: true, message: '请选择咨询类型', trigger: 'change' }],
  description: [
    { required: true, message: '请填写问题描述', trigger: 'blur' },
    { min: 10, max: 500, message: '问题描述长度应在10-500字之间', trigger: 'blur' }
  ]
}

// 表单引用
const appointmentFormRef = ref()

// 提交预约
const submitting = ref(false)

// 支付相关数据
const paymentInfo = ref<PaymentInfo>({
  orderNo: '',
  amount: 0,
  status: 'PENDING',
  paymentUrl: ''
})

// 支付状态文本

// 添加必要的响应式变量

// 修改表单相关变量

// 修改支付状态检查函数

// 定时检查支付状态
let checkInterval: number | null = null;

const startCheckingPaymentStatus = async (orderNo: string) => {
  if (!orderNo) {
    console.error('没有订单号，无法检查支付状态');
    return;
  }

  // 创建一个函数来检查支付状态
  const checkStatus = async () => {
    try {
      const res = await checkPaymentStatus(orderNo);
      console.log('支付状态查询结果:', res);

      if (res.code === 200) {
        if (res.data === 'SUCCESS') {
          ElMessage.success('支付成功');
          // 更新支付状态
          paymentInfo.value.status = 'SUCCESS';
          // 清除定时器
          if (checkInterval) {
            clearInterval(checkInterval);
            checkInterval = null;
          }
        }
      }
    } catch (error) {
      console.error('查询支付状态失败:', error);
    }
  };

  // 立即执行一次
  await checkStatus();
  
  // 设置定时器，每3秒检查一次
  checkInterval = setInterval(checkStatus, 3000);
};

const stopCheckingPaymentStatus = () => {
  console.log('停止轮询支付状态');
  if (checkInterval) {
    clearInterval(checkInterval);
    checkInterval = null;
  }
}

// 在组件卸载时清除定时器
onUnmounted(() => {
  stopCheckingPaymentStatus()
})

// 处理确认并支付
const handleConfirmAndPay = async () => {
  if (submitting.value) return;
  if (!paymentInfo.value.paymentUrl) {
    ElMessage.warning('支付链接不存在');
    return;
  }
  
  try {
    submitting.value = true;
    
    // 打开支付链接
    window.open(paymentInfo.value.paymentUrl, '_blank');
    
    // 显示支付提示
    ElMessageBox.alert(
      '支付页面已在新窗口打开，请完成支付。支付完成后系统会自动处理您的预约。',
      '支付提示',
      {
        confirmButtonText: '我知道了',
        type: 'info',
        callback: () => {
          // 开始轮询支付状态
          startCheckingPaymentStatus(paymentInfo.value.orderNo);
        }
      }
    );
  } catch (error) {
    console.error('支付失败:', error);
    ElMessage.error('支付失败，请重试');
  } finally {
    submitting.value = false;
  }
};

// 格式化日期
const formatDate = (date: Date): string => {
  return date.toLocaleDateString('zh-CN', { 
    year: 'numeric',
    month: 'long',
    day: 'numeric',
    weekday: 'long'
  })
}

// 检查是否可以进入下一步
const canGoNext = computed(() => {
  switch (currentStep.value) {
    case 0:
      return !!selectedCounselor.value
    case 1:
      return !!selectedTime.value
    case 2:
      return appointmentForm.value.type && appointmentForm.value.description
    default:
      return true
  }
})

// 获取咨询类型标签

// 年份切换
const changeYear = (delta: number) => {
  const date = new Date(selectedDate.value)
  date.setFullYear(date.getFullYear() + delta)
  selectedDate.value = date
}

// 检查时间是否可用

// 加载可用时间段
const loadAvailableTimeSlots = async (date: Date) => {
  if (!selectedCounselor.value) {
    console.log('未选择咨询师，跳过加载时间段')
    availableTimeSlots.value = []
    return
  }
  
  const params = {
    counselorId: selectedCounselor.value.id,
    date: formatDateToString(date)
  }
  console.log('请求参数:', params)
  
  try {
    const { code, data, message } = await getAvailableTimeSlots(params)
    console.log('API响应:', { code, data, message })
    
    if (code === 200) {
      availableTimeSlots.value = Array.isArray(data) ? data : []
      console.log('可用时间段:', availableTimeSlots.value)
    } else {
      console.error('获取可用时间段失败:', message)
      ElMessage.error(message || '获取可用时间段失败')
      availableTimeSlots.value = []
    }
  } catch (error) {
    console.error('获取可用时间段失败:', error)
    ElMessage.error('获取可用时间段失败')
    availableTimeSlots.value = []
  }
}

// 检查日期是否有已排班的时间段
const hasScheduledSlots = (day: string): boolean => {
  if (!selectedCounselor.value) return false

  const checkDate = new Date(day)
  const now = new Date()
  now.setHours(0, 0, 0, 0)
  
  // 过去的日期不显示
  if (checkDate < now) return false
  
  const formattedDay = formatDateToString(checkDate)
  const currentFormattedDay = formatDateToString(selectedDate.value)
  
  // 如果是当前选中的日期，检查是否有可用时间段
  if (formattedDay === currentFormattedDay) {
    // 确保有时间段且至少有一个是可预约的
    return availableTimeSlots.value.length > 0 && 
           availableTimeSlots.value.some(slot => slot.status === 'AVAILABLE')
  }
  
  // 对于其他日期，默认返回 false，需要点击后才会加载具体时间段
  return false
}

// 获取指定日期的时间段
const getDateTimeSlots = (day: string): any[] => {
  const formattedDay = formatDateToString(new Date(day))
  const currentFormattedDay = formatDateToString(selectedDate.value)
  
  // 如果是当前选中的日期，返回已加载的时间段
  if (formattedDay === currentFormattedDay) {
    // 只返回状态为 AVAILABLE 的时间段
    return availableTimeSlots.value.filter(slot => slot.status === 'AVAILABLE')
  }
  
  // 否则返回空数组
  return []
}

// 检查时间段是否可用
const isSlotAvailable = (slot: any): boolean => {
  return slot && slot.status === 'AVAILABLE'
}

// 获取时间段状态文本
const getSlotStatusText = (slot: any): string => {
  if (!slot) return '未排班'
  return slot.displayText
}

// 获取时间段标签类型
const getSlotTagType = (slot: any): string => {
  if (!slot) return 'info'
  
  switch (slot.status) {
    case 'AVAILABLE':
      return 'success'  // 可预约显示绿色
    case 'UNSCHEDULED':
      return 'info'     // 未排班显示灰色
    case 'EXPIRED':
      return 'info'     // 已过期显示灰色
    case 'CONFIRMED':
      return 'warning'  // 已预约显示黄色
    case 'BOOKED':
    case 'PENDING':
    case 'APPROVED':
      return 'warning'  // 其他预约相关状态显示黄色
    case 'REJECTED':
    case 'CANCELLED':
      return 'danger'   // 拒绝和取消显示红色
    case 'COMPLETED':
      return 'info'     // 已完成显示灰色
    default:
      return 'info'
  }
}

// 检查是否是当前月份的日期
const isCurrentMonth = (data: any): boolean => {
  const currentDate = selectedDate.value
  const cellDate = new Date(data.day)
  return currentDate.getFullYear() === cellDate.getFullYear() &&
         currentDate.getMonth() === cellDate.getMonth()
}

// 检查是否是过去的日期
const isPastDate = (day: string): boolean => {
  const date = new Date(day)
  const now = new Date()
  now.setHours(0, 0, 0, 0)
  return date < now
}

// 修改日期点击处理函数
const handleDateClick = (day: string) => {
  if (!selectedCounselor.value) {
    ElMessage.warning('请先选择咨询师')
    return
  }
  
  const clickedDate = new Date(day)
  const now = new Date()
  now.setHours(0, 0, 0, 0)
  
  if (clickedDate < now) {
    ElMessage.warning('不能选择过去的日期')
    return
  }
  
  // 如果点击了不同的日期，清空已选择的时间
  if (selectedDay.value !== day) {
    selectedTime.value = ''
  }
  
  selectedDay.value = day
  selectedDate.value = new Date(day)
  loadAvailableTimeSlots(new Date(day))
}

// 修改日历头部格式化方法

// 修改时间选择处理方法
const handleTimeSelect = (time: string) => {
  selectedTime.value = time.split('-')[0]
}

// 月份切换
const selectPrevMonth = () => {
  const date = new Date(selectedDate.value)
  date.setMonth(date.getMonth() - 1)
  selectedDate.value = date
}

const selectNextMonth = () => {
  const date = new Date(selectedDate.value)
  date.setMonth(date.getMonth() + 1)
  selectedDate.value = date
}

// 监听日期和咨询师变化
watch([selectedDate, selectedCounselor], async ([newDate, newCounselor], [oldDate, oldCounselor]) => {
  if (newDate && newCounselor) {
    // 只有当日期或咨询师发生实际变化时才重新加载
    if (
      !oldDate || 
      !oldCounselor || 
      formatDateToString(newDate) !== formatDateToString(oldDate) || 
      newCounselor.id !== oldCounselor?.id
    ) {
      // 清空选中状态
      selectedTime.value = ''
      selectedDay.value = formatDateToString(newDate)
      await loadAvailableTimeSlots(newDate)
    }
  }
}, { immediate: true })

// 处理专业领域标签
const parseSpecialty = (specialty: unknown): string[] => {
  if (Array.isArray(specialty)) {
    return specialty
  }
  try {
    return typeof specialty === 'string' 
      ? JSON.parse(specialty)
      : []
  } catch {
    return typeof specialty === 'string'
      ? specialty.split(',')
      : []
  }
}

// 修改表单验证函数

// 处理支付

onMounted(() => {
  loadCounselors()
})

const getPaymentStatusType = (status: string) => {
  const typeMap: Record<string, string> = {
    'PENDING': 'warning',
    'SUCCESS': 'success',
    'FAILED': 'danger',
    'REFUNDED': 'info'
  }
  return typeMap[status] || 'info'
}

const getPaymentStatusLabel = (status: string) => {
  const labelMap: Record<string, string> = {
    'PENDING': '待支付',
    'SUCCESS': '支付成功',
    'FAILED': '支付失败',
    'REFUNDED': '已退款'
  }
  return labelMap[status] || status
}

// 添加新的跳转函数
const goToAppointmentList = () => {
  router.push('/counseling/appointment')
}

// 添加日历标题的计算属性
const calendarTitle = computed(() => {
  const date = selectedDate.value
  if (!(date instanceof Date) || isNaN(date.getTime())) {
    return '日期无效'
  }
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  return `${year}年${month}月`
})
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
  
  .box-card {
    margin-bottom: 20px;
  }

  .steps {
    margin-bottom: 30px;
  }

  .step-content {
    min-height: 400px;
    margin: 20px 0;
  }

  .counselor-card {
    height: 100%;

    
    &.selected {
      border-color: var(--el-color-primary);
      box-shadow: 0 0 10px rgba(var(--el-color-primary-rgb), 0.2);
    }

    .counselor-info {
      .header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 10px;

        h3 {
          margin: 0;
          font-size: 18px;
        }

        .title {
          color: var(--el-text-color-secondary);
        }
      }

      .specialty-tags {
        margin: 10px 0;
        display: flex;
        flex-wrap: wrap;
        gap: 8px;
        
        .specialty-tag {
          border-radius: 12px;
          padding: 0 12px;
          font-size: 12px;
        }
      }

      .rating {
        display: flex;
        align-items: center;
        margin-bottom: 10px;

        .count {
          margin-left: 10px;
          color: var(--el-text-color-secondary);
          font-size: 14px;
        }
      }

      .introduction {
        margin-bottom: 15px;
        color: var(--el-text-color-regular);
        font-size: 14px;
        line-height: 1.5;
      }

      .el-button {
        width: 100%;
        
        &.is-selected {
          background-color: var(--el-color-success);
          border-color: var(--el-color-success);
        }
      }
    }
  }

  .time-slots-container {
    padding: 20px;
    background-color: var(--el-bg-color-page);
    border-radius: 4px;

    h3 {
      margin-top: 0;
      margin-bottom: 20px;
    }

    .time-slot {
      display: flex;
      flex-direction: column;
      align-items: center;
      padding: 15px;
      margin-bottom: 10px;
      border: 1px solid var(--el-border-color);
      border-radius: 4px;
      cursor: pointer;
      transition: all 0.2s ease-out;
      
      .time {
        font-size: 16px;
        font-weight: bold;
        margin-bottom: 8px;
        transition: color 0.2s ease-out;
        color: var(--el-text-color-primary);
      }

      .el-tag {
        width: 100%;
        text-align: center;
        transition: all 0.2s ease-out;

        &.available {
          background-color: var(--el-color-success-light-9);
          color: var(--el-color-success);
          border-color: var(--el-color-success-light-5);
        }
      }

      &:hover:not(.disabled) {
        border-color: var(--el-color-primary);
        
        &:not(.selected) {
          .time {
            color: var(--el-color-primary);
          }
        }
      }

      &.selected {
        background-color: var(--el-color-primary);
        border-color: var(--el-color-primary);

        &:hover {
          background-color: var(--el-color-primary-dark-2);
          border-color: var(--el-color-primary-dark-2);
        }

        .time {
          color: white;
        }

        .el-tag {
          background-color: transparent;
          border-color: rgba(255, 255, 255, 0.3);
          color: white;
        }
      }

      &.disabled {
        background-color: var(--el-bg-color-page);
        cursor: not-allowed;
        opacity: 0.6;
      }
    }
  }

  .appointment-form {
    max-width: 600px;
    margin: 0 auto;
    padding: 20px;
    
    .el-select {
      width: 100%;
    }
    
    .el-textarea {
      width: 100%;
    }
  }

  .confirmation {
    max-width: 800px;
    margin: 0 auto;
  }

  .step-actions {
    display: flex;
    justify-content: center;
    gap: 20px;
    margin-top: 30px;
    padding-top: 20px;
    border-top: 1px solid var(--el-border-color-light);
  }

  .calendar-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 20px;

    .calendar-title {
      font-size: 16px;
      font-weight: bold;
    }

    .calendar-controls {
      display: flex;
      gap: 10px;

      .year-control,
      .month-control {
        margin-left: 10px;
      }
    }
  }

  .time-slots-wrapper {
    margin-top: -12px; // 对齐日历顶部

    .time-slots-container {
      background-color: var(--el-bg-color-page);
      border-radius: 4px;
      padding: 20px;
      height: 100%;
      
      h3 {
        margin-top: 0;
        margin-bottom: 20px;
        font-size: 16px;
        font-weight: bold;
      }
    }
  }

  :deep(.el-calendar) {
    --el-calendar-header-height: auto;
    
    .el-calendar__header {
      padding: 12px 0;
    }
    
    .el-calendar__body {
      padding: 12px 20px 35px;
    }

    th {
      text-align: center;
      padding: 12px 0;
      color: var(--el-text-color-regular);
      font-weight: 400;
    }

    td {
      text-align: center;
      height: 85px;
      padding: 4px;
    }

    td.prev,
    td.next {
      .calendar-cell {
        opacity: 0.5;
        pointer-events: none;
      }
    }

    td.current {
      .calendar-cell {
        &.disabled {
          opacity: 0.5;
          pointer-events: none;
          
          .slot-indicator {
            display: none;
          }
        }
      }
    }
  }

  .calendar-cell {
    position: relative;
    height: 100%;
    min-height: 80px;
    display: flex;
    flex-direction: column;
    cursor: pointer;
    
    .date-text {
      position: absolute;
      top: 4px;
      right: 8px;
      font-size: 14px;
      font-weight: 500;
      z-index: 2;
      color: var(--el-text-color-primary);
      background-color: transparent;
      padding: 2px 4px;
      border-radius: 2px;
    }
    
    .schedule-content {
      flex: 1;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: flex-start;
      padding: 4px;
      padding-top: 28px; // 为日期文本留出空间
      gap: 4px;
      overflow-y: auto;
      min-height: 0;
      
      &::-webkit-scrollbar {
        width: 4px;
      }
      
      &::-webkit-scrollbar-thumb {
        background-color: var(--el-border-color);
        border-radius: 2px;
      }
      
      .time-slot {
        width: 100%;
        
        .schedule-tag {
          width: 100%;
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 2px 4px;
          margin: 1px 0;
          font-size: 11px;
          
          .slot-status {
            font-size: 11px;
            margin-left: 4px;
          }
        }
      }
    }
  }

  :deep(.el-calendar-table) {
    td {
      &.prev,
      &.next {
        .calendar-cell {
          opacity: 0.5;
          pointer-events: none;
        }
      }
      
      &.current {
        .calendar-cell {
          &:hover {
            background-color: transparent !important;
          }
          
          &.selected {
            background-color: var(--el-color-primary-light-9);
          }
        }
      }
    }
  }

  :deep(.el-calendar-day) {
    &:hover {
      background-color: transparent !important;
    }
  }

  .payment-container {
    padding: 20px;
    max-width: 600px;
    margin: 0 auto;

    .payment-card {
      border-radius: 8px;
      box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);

      .payment-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0 0 16px;

        .payment-title {
          font-size: 18px;
          font-weight: bold;
          color: #303133;
        }
      }

      .payment-content {
        padding: 16px 0;

        .order-no {
          font-family: Monaco, monospace;
          color: #606266;
        }

        .amount {
          font-size: 20px;
          font-weight: bold;
          color: #f56c6c;
        }

        .payment-actions {
          margin-top: 24px;
          text-align: center;
        }
      }
    }
  }
}
</style> 
